package com.chinaedu.oc.action.commodity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chinaedu.oc.action.base.BaseController;
import com.chinaedu.oc.bo.ProductQuery;
import com.chinaedu.oc.constant.Constant;
import com.chinaedu.oc.context.Common.Session;
import com.chinaedu.oc.dao.managegroup.ManageGroupDao;
import com.chinaedu.oc.dao.manageuser.ManageUserDao;
import com.chinaedu.oc.entity.common.Area;
import com.chinaedu.oc.entity.common.CodeList;
import com.chinaedu.oc.entity.common.Grade;
import com.chinaedu.oc.entity.common.Level;
import com.chinaedu.oc.entity.common.Specialty;
import com.chinaedu.oc.entity.common.System;
import com.chinaedu.oc.entity.managegroup.ManageGroup;
import com.chinaedu.oc.entity.manageuser.ManageUser;
import com.chinaedu.oc.po.auditrecord.Auditrecord;
import com.chinaedu.oc.po.commodity.Commodity;
import com.chinaedu.oc.po.commodity.CommodityArea;
import com.chinaedu.oc.po.commodity.CommodityEducational;
import com.chinaedu.oc.po.commodity.CommodityGrade;
import com.chinaedu.oc.po.commodity.CommodityLevel;
import com.chinaedu.oc.po.commodity.CommodityProduct;
import com.chinaedu.oc.po.commodity.CommodityRelationship;
import com.chinaedu.oc.po.commodity.CommoditySaledepartment;
import com.chinaedu.oc.po.commodity.CommoditySpecialty;
import com.chinaedu.oc.po.commodity.CommodityUserType;
import com.chinaedu.oc.po.commodity.dto.AuditDto;
import com.chinaedu.oc.po.commodity.dto.CommodityBaseDto;
import com.chinaedu.oc.po.commodity.dto.CommodityListBaseDto;
import com.chinaedu.oc.po.commodity.dto.QueryCondition;
import com.chinaedu.oc.po.dto.PubOutputDto;
import com.chinaedu.oc.po.product.Product;
import com.chinaedu.oc.po.product.ProductArea;
import com.chinaedu.oc.po.product.dto.QueryProductInput;
import com.chinaedu.oc.po.product.dto.QueryProductOutput;
import com.chinaedu.oc.po.productline.ProductLine;
import com.chinaedu.oc.po.saledate.Desc;
import com.chinaedu.oc.po.saledate.Picture;
import com.chinaedu.oc.po.saledate.Saledate;
import com.chinaedu.oc.po.saledate.Videos;
import com.chinaedu.oc.po.saledate.dto.SaledateInput;
import com.chinaedu.oc.service.cache.ProductLineCacheServ;
import com.chinaedu.oc.service.cache.StaticCacheServ;
import com.chinaedu.oc.uri.IName;
import com.chinaedu.oc.util.common.StringUtil;
import com.chinaedu.oc.util.excel.ExcelCreater;
import com.chinaedu.oc.util.http.HttpHelper;
import com.chinaedu.oc.util.http.HttpRequestException;
import com.chinaedu.oc.vo.CommodityVO;

/**
 *
* @ClassName: CommodityAction
* @Description: TODO(商品与定价操作)
* @Author: wangchao101
* @Date: 2017年5月15日 下午3:41:42
*
 */
@Controller
@RequestMapping("/web/commodity")
public class CommodityAction extends BaseController{
    @Autowired
    private StaticCacheServ cacheServ;
    @Autowired
    private ProductLineCacheServ productLineCacheServ;
    @Autowired
    private ManageUserDao manageUserDao;
    @Autowired
    private ManageGroupDao manageGroupDao;
    /**
     * 新增.编辑.定价商品
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/insertOrUpdateCommodity")
    @ResponseBody
    public PubOutputDto insertOrUpdateCommodity(@RequestBody Commodity commodity,HttpSession session) throws HttpRequestException{
        //从session中获取用户信息
        ManageUser user = (ManageUser) session.getAttribute(Session.manageUserLogin.name());
        //如果商品ID为空 说明是新增.保存新增用户ID.否则保存修改用户ID
        if(StringUtils.isBlank(commodity.getId())){
            commodity.setCreatorId(user.getUserId());
        }else{
            commodity.setModifyUser(user.getUserId());
        }
        PubOutputDto pubOutputDto = null;
        if(Constant.COMMODITY_IS_SINGLEPRODUCT_B.equals(commodity.getType())){
            List<CommodityRelationship> commodityRelationships = new ArrayList<CommodityRelationship>();
            List<CommodityProduct> commodityProducts = commodity.getCommodityProducts();
            CommodityRelationship commodityRelationship = null;
            for (CommodityProduct commodityProduct : commodityProducts) {
                commodityRelationship = new  CommodityRelationship();
                commodityRelationship.setChildId(commodityProduct.getCommodityId());
                commodityRelationship.setSingleCurrentPrice(commodityProduct.getProductCurrentPrice());
                commodityRelationships.add(commodityRelationship);
            }
            commodity.setCommodityRelationship(commodityRelationships);
            commodity.setCommodityProducts(null);
            commodity.setCommodityProduct(null);

            pubOutputDto = HttpHelper.sendRequest(IName.Commodity.ADD_UPDATE_COMMODITY, commodity, PubOutputDto.class);
        }else{
            List<CommodityProduct> commodityProducts = commodity.getCommodityProducts();
            if(commodityProducts != null){
                CommodityProduct commodityProduct = new CommodityProduct();
                commodityProduct = commodityProducts.get(0);
                commodity.setCommodityProduct(commodityProduct);
            }
            pubOutputDto = HttpHelper.sendRequest(IName.Commodity.SYCHRONIZE_COMMODITY, commodity, PubOutputDto.class);

        }
        return pubOutputDto;
    }
    /**
     * 删除商品
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/delCommodity")
    @ResponseBody
    public PubOutputDto delCommodity(HttpServletRequest request) throws HttpRequestException{
    	String[] ids = request.getParameterValues("ids[]");
        PubOutputDto pubOutputDto = HttpHelper.sendRequest(IName.Commodity.DELETE_COMMODITY, ids, PubOutputDto.class);
        return pubOutputDto;
    }
    /**
     * 提审商品
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/checkCommodity")
    @ResponseBody
    public PubOutputDto checkCommodity(HttpServletRequest request) throws HttpRequestException{
        //从session中获取用户信息
        ManageUser user = (ManageUser) request.getSession().getAttribute(Session.manageUserLogin.name());
    	String[] ids = request.getParameterValues("ids[]");
    	AuditDto auditDto = new AuditDto();
    	auditDto.setIds(Arrays.asList(ids));
    	auditDto.setSponsor(user.getUserId());
        PubOutputDto pubOutputDto = HttpHelper.sendRequest(IName.Commodity.AUDIT_COMMODITY, auditDto, PubOutputDto.class);
        return pubOutputDto;
    }
    /**
     * 导出商品
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/exportCommodity")
    public void exportCommodity(QueryCondition queryCondition,HttpServletResponse response,HttpServletRequest request) throws HttpRequestException{
        //将下拉框初始化的值设置为null
        QueryCondition newQuery = transformParams(queryCondition);
        //多条件查询出商品列表信息,返回json字符串.转换为DTO对象
        String commodityJson = HttpHelper.sendRequest(
                IName.Commodity.EXPORTCSV_COMMODITY, newQuery);
        CommodityListBaseDto<Commodity> dto = JSON.parseObject(
                commodityJson, new TypeReference<CommodityListBaseDto<Commodity>>(){});
        //将商品列表取出
        List<Commodity> listData = dto.getData();
        //新建集合封装需要导出的数据
        List<CommodityVO> list = new ArrayList<>();
        if(null != listData && listData.size() >0){
            //根据审核状态和销售期更新销售状态
            setSaleStatus(listData);
            for (Commodity commodity : listData) {
                //创建VO类封装导出需要的数据
                CommodityVO commodityVO = new CommodityVO();
                commodityVO.setCommodityCode(commodity.getCommodityCode());
                commodityVO.setCommodityName(commodity.getCommodityName());
                commodityVO.setGradeName(commodity.getGradeName());
                commodityVO.setSpecialtyName(commodity.getSpecialtyName());
                commodityVO.setCurrentPrice(commodity.getCurrentPrice());
                commodityVO.setProductLineName(commodity.getProductLineName());
                commodityVO.setCreateDate(commodity.getCreateDate());
                commodityVO.setSaleStatus(commodity.getSaleStatus());
                //根据状态码从缓存中取出对应的状态名称
                commodityVO.setIsSingleProduct(
                        cacheServ.queryData("commodity_type", commodity.getIsSingleProduct(), CodeList.class).getValue());
                commodityVO.setAuditStatus(
                        cacheServ.queryData("review_status", commodity.getAuditStatus(), CodeList.class).getValue());
                list.add(commodityVO);
            }
        }
        String[] fields = {"commodityCode","commodityName","isSingleProduct","gradeName",
                "specialtyName","currentPrice","productLineName","auditStatus","saleStatus","createDate"};
        String[] head = {"商品编码","商品名称","组成","年级","学科","现价","产品线","审核状态","销售状态","创建时间"};
        ExcelCreater<CommodityVO> creater = new ExcelCreater<>();
        try {
            creater.createExcel(list , fields , head, "商品导出信息", response,request);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 多条件分页查询
     * @param queryCondition
     * @return
     * @throws HttpRequestException
     * @throws IOException
     */
    @RequestMapping("/findCommodityListByCase")
    @ResponseBody
    public Object findCommodityListByCase(@ModelAttribute QueryCondition queryCondition,HttpServletRequest request,
            Integer start,Integer length) throws HttpRequestException, IOException{
        //将前台传递的审核状态字符串转换为集合保存到查询入参中
        if(StringUtils.isNotBlank(queryCondition.getAuditStatusIdsStr())){
            String ids = queryCondition.getAuditStatusIdsStr();
            String[] str = ids.split(",");
            queryCondition.setAuditStatusIds(Arrays.asList(str));
        }
        //将前台传递的排序字段重新转换为数据库需要字段
        if(StringUtils.isNotBlank(queryCondition.getOrderName())){
            String orderName = "";
            orderName = queryCondition.getOrderName();
            queryCondition.setOrderName("f_"+StringUtil.underscoreName(orderName));
        }
        //设置分页查询参数
        queryCondition.setCurrentPage(start);
        queryCondition.setPageSize(length);
        QueryCondition newQuery = transformParams(queryCondition);
        //多条件查询出商品列表信息,返回json字符串.转换为DTO对象
        String commodityJson = HttpHelper.sendRequest(
                IName.Commodity.FINDCOMMODITYLIST_COMMODITY, newQuery);
        CommodityListBaseDto<Commodity> dto = JSON.parseObject(
                commodityJson, new TypeReference<CommodityListBaseDto<Commodity>>(){});
        //将商品列表取出.循环判断每个商品的审核状态和销售期来添加销售状态
        List<Commodity> list = dto.getData();
        if(null != list && list.size() >0){
            //根据审核状态和销售期更新销售状态
            setSaleStatus(list);
            return dto;
        }else{
            Map<Object,Object> map = new HashMap<>();
            map.put("data", new ArrayList<>());
            map.put("recordsFiltered", 0);
            map.put("recordsTotal", 0);
            map.put("status", true);
            return map;
        }
    }

    /**
     * 根据审核状态和销售期更新销售状态
     * @param list
     * @return
     * @throws HttpRequestException
     */
    private List<Commodity> setSaleStatus(List<Commodity> list) throws HttpRequestException{
        for (Commodity commodity : list) {
            //根据审核状态和销售期更新销售状态
            if(Constant.COMMODITY_REVIEW_STATUS_D.equals(commodity.getAuditStatus())){
                if(Constant.COMMODITY_IS_HAS_SALEDATE_A == commodity.getIsHasSaledate()){
                    String saleJson = HttpHelper.sendRequest(
                            IName.SaleDate.FIND_FINDSALEBYDATE, commodity.getId());
                    CommodityBaseDto<Saledate> saleDateDto = JSON.parseObject(
                            saleJson, new TypeReference<CommodityBaseDto<Saledate>>(){});
                    Saledate saledate = saleDateDto.getData();
                    if(null == saledate){
                        commodity.setSaleStatus("已停售");
                    }else{
                        commodity.setSaleStatus("已开售");
                    }
                }else{
                    commodity.setSaleStatus("已开售");
                }
            }else{
                commodity.setSaleStatus("已停售");
            }
        }
        return list;
    }
    /**
     * 打包商品时,查询单品列表(不分页)
     * @param queryCondition
     * @return
     * @throws HttpRequestException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/findSingleCommodityListByCase")
    @ResponseBody
    public CommodityListBaseDto<Commodity> findSingleCommodityListByCase(QueryCondition queryCondition) throws HttpRequestException{
        QueryCondition newQuery = transformParams(queryCondition);
        CommodityListBaseDto<Commodity> dto = HttpHelper.sendRequest(
                IName.Commodity.SINGLECOMMODITYLIST_COMMODITY, newQuery, CommodityListBaseDto.class);
        return dto;
    }
    /**
     * 定价或编辑时查询商品信息
     * @param queryCondition
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/findCommodityById")
    @ResponseBody
    public Map<String,Object> findCommodityById(CommodityVO commodityVO) throws HttpRequestException{
        Map<String,Object> jsonMap = new HashMap<String,Object>();
        //根据单品ID查询出商品信息,返回json字符串转换为DTO对象
        String json = HttpHelper.sendRequest(IName.Commodity.FINDBYID_COMMODITY, commodityVO);
        CommodityBaseDto<Commodity> dto = JSON.parseObject(
                json, new TypeReference<CommodityBaseDto<Commodity>>(){});
        //取出商品信息封装进map
        Commodity data = dto.getData();
        //标志位,表示转义数据方法走的是定价或编辑商品的数据格式
        boolean flag = true;
        //调用封装数据方法
        Map<String, Object> map = packData(data,flag);
        jsonMap.put("data", map);
        jsonMap.put("status", true);
        return jsonMap;
    }
    /**
     * 查看商品详情信息
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/findCommodityDetail")
    @ResponseBody
    public Map<String, Object> findCommodityDetail(CommodityVO commodityVO,HttpSession session) throws HttpRequestException{
        //从session中获取用户信息
        ManageUser user = (ManageUser) session.getAttribute(Session.manageUserLogin.name());
        Map<String, Object> jsonMap = new HashMap<>();
        //根据单品ID查询出商品信息,返回json字符串转换为DTO对象
        String json = HttpHelper.sendRequest(IName.Commodity.FINDDETAIL_COMMODITY, commodityVO);
        CommodityBaseDto<Commodity> dto = JSON.parseObject(
                json, new TypeReference<CommodityBaseDto<Commodity>>(){});
        Commodity data = dto.getData();
        List<Saledate> saledates = data.getSaledates();
        for (Saledate saledate : saledates) {
            saledate.setCreator(user.getRealName());
        }
        //标志位,表示转义方法走的是查询商品需要的数据格式
        boolean flag = false;
        Map<String, Object> map = packData(data,flag);
        //从出参对象中获取审核信息列表.循环列表根据发起人ID获取真实姓名保存.根据审核人ID获取审核人真实姓名和当前节点
        List<Auditrecord> auditrecords = data.getAuditrecords();
        if(null != auditrecords && auditrecords.size() > 0){
            for (Auditrecord auditrecord : auditrecords) {
                if(StringUtils.isNotBlank(auditrecord.getSponsor())){
                    ManageUser manageUser = manageUserDao.findUserById(auditrecord.getSponsor());
                    auditrecord.setSponsor(manageUser.getRealName());
                }
                if(StringUtils.isNotBlank(auditrecord.getAuditor())){
                    ManageUser manageUser2 = manageUserDao.findUserById(auditrecord.getAuditor());
                    auditrecord.setAuditor(manageUser2.getRealName());
                    String groupId = manageUser2.getGroupId();
                    ManageGroup manageGroup = manageGroupDao.findGroupById(groupId);
                    auditrecord.setCurrentNode(manageGroup.getGroupName());
                }
            }
        }
        map.put("originalPrice", data.getOriginalPrice());
        map.put("currentPrice", data.getCurrentPrice());
        map.put("discount", data.getDiscount());
        map.put("saledate", data.getSaledate());
        map.put("createDate", data.getCreateDate());
        map.put("saleDateList", saledates);
        map.put("auditList", auditrecords);
        jsonMap.put("data", map);
        jsonMap.put("status", true);
        return jsonMap;
    }
    /**
     * 商品上架
     * @param queryCondition
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/groupCommodity")
    @ResponseBody
    public PubOutputDto groupCommodity(CommodityVO commodityVO) throws HttpRequestException{
        PubOutputDto pubOutputDto = HttpHelper.sendRequest(IName.Commodity.GROUP_COMMODITY, commodityVO, PubOutputDto.class);
        return pubOutputDto;
    }
    /**
     * 添加或者修改销售期
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/insertOrUpdateSaleDate")
    @ResponseBody
    public PubOutputDto insertOrUpdateSaleDate(@RequestBody SaledateInput saledateInput) throws HttpRequestException{
        PubOutputDto pubOutputDto = HttpHelper.sendRequest(IName.SaleDate.ADD_UPDATE_SALEDATE, saledateInput, PubOutputDto.class);
        return pubOutputDto;
    }
    /**
     * 查询商品的销售日期列表
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/querySaleDateList")
    @ResponseBody
    public CommodityListBaseDto<Saledate> querySaleDateList(CommodityVO commodityVO) throws HttpRequestException{
        CommodityListBaseDto<Saledate> dto = HttpHelper.sendRequest(
                IName.SaleDate.FIND_SALEDATE, commodityVO, CommodityListBaseDto.class);
        return dto;
    }

    /**
     * 查询商品描述信息
     * @param saledateId
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/querySaledateDesc")
    @ResponseBody
    public  Map<String, Object> querySaledateDesc(String saledateId) throws HttpRequestException {
    	Map<String, String> map = new HashMap<String,String>();//saledateId
    	map.put("saledateId", saledateId);
    	//FIND_FINDBYSALEID
    	String sendRequest = HttpHelper.sendRequest(IName.SaleDate.FIND_FINDBYSALEID, map);
    	CommodityBaseDto<Saledate> saledateList = JSON.parseObject(sendRequest,  new TypeReference<CommodityBaseDto<Saledate>>(){});
    	Saledate saledate = saledateList.getData();

    	 Map<String, Object> jsonMap = new HashMap<>();
         Map<String, Object> descMap = new HashMap<>();

         if(null != saledate){
             List<Desc> descList = saledate.getDescList();
             if(null != descList && descList.size() >0){
                 descMap.put("descList", descList);
             }
             List<Picture> pictureList = saledate.getPictureList();
             if(null != pictureList && pictureList.size() >0){
                 descMap.put("pictureList",pictureList );
             }
             List<Videos> videosList = saledate.getVideosList();
             if(null != videosList && videosList.size() >0){
                 descMap.put("videosList", videosList);
             }
         }
         descMap.put("saledateId", saledateId);
         jsonMap.put("status", saledateList.getStatus());
         jsonMap.put("msg", saledateList.getMsg());
         jsonMap.put("data", descMap);
         return jsonMap;
    }

    /**
     * 修改或者保存销售日期的描述信息
     * @param saledateId
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/insertOrUpdateMsg")
    @ResponseBody
    public  PubOutputDto insertOrUpdateMsg(@RequestBody Saledate saledate) throws HttpRequestException {
    	PubOutputDto dto = HttpHelper.sendRequest(IName.SaleDate.INSERTORUPDATEMSG_SALEDATE, saledate, PubOutputDto.class);
    	return dto;
    }


    /**
     * 商品复制
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/copyCommodity")
    @ResponseBody
    public PubOutputDto copyCommodity(HttpServletRequest request) throws HttpRequestException{
    	 String[] ids = request.getParameterValues("ids[]");
        PubOutputDto pubOutputDto = HttpHelper.sendRequest(IName.Commodity.COPY_COMMODITY, ids, PubOutputDto.class);
        return pubOutputDto;
    }
    /**
     * 商品审核通过或者驳回
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/isPassed")
    @ResponseBody
    public PubOutputDto isPassed(CommodityVO commodityVO,HttpSession session) throws HttpRequestException{
      //从session中获取用户信息
        ManageUser user = (ManageUser) session.getAttribute(Session.manageUserLogin.name());
        commodityVO.setAuditor(user.getUserId());
        PubOutputDto pubOutputDto = HttpHelper.sendRequest(IName.Commodity.ISPASSED_COMMODITY, commodityVO, PubOutputDto.class);
        return pubOutputDto;
    }
    /**
     * 根据单品ID查询多个单品信息
     * @param commodityVO
     * @return
     * @throws HttpRequestException
     */
    @RequestMapping("/querySingleCommodityList")
    @ResponseBody
    public Map<String,Object> querySingleCommodityList(HttpServletRequest request) throws HttpRequestException{
        //取出多个要打包的单品ID数组
        String[] ids = request.getParameterValues("ids[]");
        //根据单品ID查询出单品信息,返回json字符串转换为DTO对象
        String json = HttpHelper.sendRequest(
                IName.Commodity.COMMITSINGLELIST_COMMODITY, Arrays.asList(ids));
        CommodityListBaseDto<CommodityProduct> dto = JSON.parseObject(
                json, new TypeReference<CommodityListBaseDto<CommodityProduct>>(){});
        //从DTO中取出单品列表,循环列表
        List<CommodityProduct> data = dto.getData();
        //创建集合保存需要返回页面的VO类
        List<CommodityVO> list = new ArrayList<>();
        for (CommodityProduct comOut : data) {
            //创建VO类封装接口返回数据
            CommodityVO vo = new CommodityVO();
            vo.setCommodityId(comOut.getCommodityId());
            vo.setCommodityName(comOut.getCommodityName());
            vo.setUnitPrice(comOut.getUnitPrice());
            vo.setNumber(comOut.getNumber());
            vo.setProductOriginalPrice(comOut.getProductOriginalPrice());
            vo.setProductCurrentPrice(comOut.getProductCurrentPrice());
            //从出参中取出对应的产品线ID,从缓存中取出产品线
            String productLineId = comOut.getProductSource();
            vo.setProductSource(productLineId);
            ProductLine productLine = productLineCacheServ.getProductLine(productLineId);
            if(null != productLine){
                vo.setProductLineName(productLine.getName());
            }
            //从出参中取出对应的产品ID
            String productId = comOut.getProductId();
            //创建查询产品信息的入参对象,将产品ID封装进去
            QueryProductInput productInput = new QueryProductInput();
            productInput.setProductQuery(new ProductQuery());
            productInput.getProductQuery().setId(productId);
            //请求产品接口返回出参对象
            QueryProductOutput productOutput = HttpHelper.sendRequest(
                    IName.Product.QUERY_PRODUCT, productInput, QueryProductOutput.class);
            //从产品出参对象中取出产品对应地区ID集合
            List<ProductArea> listArea = productOutput.getListProductArea().get(productId);
            if(null != listArea && listArea.size() >0){
                List<String> arrayList = new ArrayList<>();
                for (ProductArea productArea : listArea) {
                    String areaName = cacheServ.queryData(Constant.AREA_DATA,productArea.getAreaId(), Area.class).getName();
                    arrayList.add(areaName);
                }
                vo.setAreaName(arrayList);
            }
            //从产品出参对象中取出产品列表,判断非空
            List<Product> productList = productOutput.getListProduct();
            if(null != productList && productList.size() >0){
                //从产品列表中取出对应的属性值(编码类型数据从缓存中取出对应的值)
                vo.setProductType(
                        cacheServ.queryData("product_type", productList.get(0).getProductType(), CodeList.class).getValue());
                vo.setBillType(
                        cacheServ.queryData("bill_type", productList.get(0).getBillType(), CodeList.class).getValue());
                vo.setUnit(
                        cacheServ.queryData("unit",productList.get(0).getUnit(),CodeList.class).getValue());
                vo.setTimeLength(productList.get(0).getTimeLength());
                vo.setExpiryLength(productList.get(0).getExpiryLength());
            }
            list.add(vo);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data", list);
        map.put("status", dto.getStatus());
        map.put("msg", dto.getMsg());
        return map;
    }

    /**
     * 根据商品信息取出单品列表封装
     * @param data
     * @return
     * @throws HttpRequestException
     */
    private List<CommodityVO> packCommodityProducts(Commodity data) throws HttpRequestException{
        //封装单品信息集合
        List<CommodityVO> commodityList = new ArrayList<>();
        //取出单品列表
        List<CommodityProduct> products = data.getCommodityProducts();
        //循环单品列表
        for (CommodityProduct commodityProduct : products) {
            //创建VO类封装接口返回数据
            CommodityVO vo = new CommodityVO();
            vo.setCommodityId(commodityProduct.getCommodityId());
            vo.setUnitPrice(commodityProduct.getUnitPrice());
            vo.setNumber(commodityProduct.getNumber());
            vo.setProductOriginalPrice(commodityProduct.getProductOriginalPrice());
            vo.setProductCurrentPrice(commodityProduct.getProductCurrentPrice());
            //从出参中取出对应的产品线ID,从缓存中取出产品线
            String productLineId = commodityProduct.getProductSource();
            vo.setProductSource(productLineId);
            ProductLine productLine = productLineCacheServ.getProductLine(productLineId);
            if(null != productLine){
                vo.setProductLineName(productLine.getName());
            }
            //从出参中取出对应的产品ID
            String productId = commodityProduct.getProductId();
            vo.setProductId(productId);
            //创建查询产品信息的入参对象,将产品ID封装进去
            QueryProductInput productInput = new QueryProductInput();
            productInput.setProductQuery(new ProductQuery());
            productInput.getProductQuery().setId(productId);
            //请求产品接口返回出参对象
            QueryProductOutput productOutput = HttpHelper.sendRequest(
                    IName.Product.QUERY_PRODUCT, productInput, QueryProductOutput.class);
            //从产品出参对象中取出产品对应地区ID集合
            List<ProductArea> listArea = productOutput.getListProductArea().get(productId);
            if(null != listArea && listArea.size() >0){
                List<String> arrayList = new ArrayList<>();
                for (ProductArea productArea : listArea) {
                    String areaName = cacheServ.queryData(Constant.AREA_DATA,productArea.getAreaId(), Area.class).getName();
                    arrayList.add(areaName);
                }
                vo.setAreaName(arrayList);
            }
            //从产品出参对象中取出产品列表,判断非空
            List<Product> productList = productOutput.getListProduct();
            if(null != productList && productList.size() >0){
                //从产品列表中取出对应的属性值(编码类型数据从缓存中取出对应的值)
                vo.setProductType(
                        cacheServ.queryData("product_type", productList.get(0).getProductType(), CodeList.class).getValue());
                vo.setBillType(
                        cacheServ.queryData("bill_type", productList.get(0).getBillType(), CodeList.class).getValue());
                vo.setUnit(
                        cacheServ.queryData("unit",productList.get(0).getUnit(),CodeList.class).getValue());
                vo.setTimeLength(productList.get(0).getTimeLength());
                vo.setExpiryLength(productList.get(0).getExpiryLength());
                vo.setCommodityName(productList.get(0).getName());
            }
            commodityList.add(vo);
        }
        return commodityList;
    }
    /**
     * 封装与商品信息关联数据
     * @param data
     * @return
     * @throws HttpRequestException
     */
    private Map<String, Object> packData(Commodity data,boolean flag) throws HttpRequestException{
        Map<String, Object> map = new HashMap<>();
        //封装销售部门集合
        List<String> deptList = new ArrayList<>();
        //封装学制集合
        List<String> studySystemList = new ArrayList<>();
        //封装学段集合
        List<String> studyLevelList = new ArrayList<>();
        //封装年级集合
        List<String> gradeList = new ArrayList<>();
        //封装学科集合
        List<String> specialtyList = new ArrayList<>();
        //封装用户类型集合
        List<String> userTypeList = new ArrayList<>();

        //取出销售部门列表,循环列表取出部门ID添加到部门集合
        List<CommoditySaledepartment> dept = data.getCommoditySaledepartments();
        if(null != dept && dept.size() >0){
            for (CommoditySaledepartment commodityDept : dept) {
                if(StringUtils.isNotBlank(commodityDept.getSaleDepartmentId())){
                    if(flag == true){
                        deptList.add(commodityDept.getSaleDepartmentId());
                    }else{
                        deptList.add(cacheServ.queryData(
                                "department", commodityDept.getSaleDepartmentId(), CodeList.class).getValue());
                    }
                }
            }
        }
        //取出学制列表,循环列表取出学制ID添加到学制集合
        List<CommodityEducational> educational = data.getCommodityEducational();
        if(null != educational && educational.size() >0){
            for (CommodityEducational commodityEducational : educational) {
                if(StringUtils.isNotBlank(commodityEducational.getEducationalId())){
                    if(flag == true){
                        studySystemList.add(commodityEducational.getEducationalId());
                    }else{
                        studySystemList.add(cacheServ.queryData(
                                Constant.SCHOOL_SYSTEM, commodityEducational.getEducationalId(), System.class).getSystemName());
                    }
                }
            }
        }
        //取出学段列表,循环列表取出学段ID添加到学段集合
        List<CommodityLevel> commodityLevels = data.getCommodityLevels();
        if(null != commodityLevels && commodityLevels.size() >0){
            for (CommodityLevel commodityLevel : commodityLevels) {
                if(StringUtils.isNotBlank(commodityLevel.getLevelId())){
                    if(flag == true){
                        studyLevelList.add(commodityLevel.getLevelId());
                    }else{
                        studyLevelList.add(cacheServ.queryData(
                                Constant.SCHOOL_LEVEL, commodityLevel.getLevelId(), Level.class).getLevelName());
                    }
                }
            }
        }
        //取出年级列表,循环列表取出年级ID添加到年级集合
        List<CommodityGrade> commodityGrade = data.getCommodityGrade();
        if(null != commodityGrade && commodityGrade.size() >0){
            for (CommodityGrade grade : commodityGrade) {
                if(StringUtils.isNotBlank(grade.getGradeId())){
                    if(flag == true){
                        gradeList.add(grade.getGradeId());
                    }else{
                        gradeList.add(cacheServ.queryData(
                                Constant.GRADE, grade.getGradeId(), Grade.class).getGradeName());
                    }
                }
            }
        }
        //取出学科列表,循环列表取出学科ID添加到学科集合
        List<CommoditySpecialty> commoditySpecialty = data.getCommoditySpecialty();
        if(null !=commoditySpecialty && commoditySpecialty.size() >0){
            for (CommoditySpecialty specialty : commoditySpecialty) {
                if(StringUtils.isNotBlank(specialty.getSpecialtyId())){
                    if(flag == true){
                        specialtyList.add(specialty.getSpecialtyId());
                    }else{
                        specialtyList.add(cacheServ.queryData(
                                Constant.SPECIALTY,specialty.getSpecialtyId(),Specialty.class).getSpecialtyName());
                    }
                }
            }
        }
        //取出用户类型列表,循环列表取出用户类型ID添加到用户类型集合
        List<CommodityUserType> commodityUserType = data.getCommodityUserType();
        if(null != commodityUserType && commodityUserType.size() >0){
            for (CommodityUserType userType : commodityUserType) {
                if(StringUtils.isNotBlank(userType.getUserTypeId())){
                    if(flag == true){
                        userTypeList.add(userType.getUserTypeId());
                    }else{
                        userTypeList.add(cacheServ.queryData(
                                "user_type", userType.getUserTypeId(), CodeList.class).getValue());
                    }
                }
            }
        }
        //创建地区ID,地区名称的字符串
        StringBuffer areaIds = new StringBuffer();
        StringBuffer areaNames = new StringBuffer();
        String areaId = "";
        String areaName = "";
        //取出地区列表,循环列表取出地区ID添加到用户类型集合
        List<CommodityArea> commodityAreas = data.getCommodityAreas();
        if(null != commodityAreas && commodityAreas.size() >0){
            for (CommodityArea area : commodityAreas) {
                //根据地区ID从缓存中获取地区名称
                String name = cacheServ.queryData(Constant.AREA_DATA, area.getAreaId(), Area.class).getName();
                areaNames.append(name);
                areaNames.append(",");
                areaIds.append(area.getAreaId());
                areaIds.append(",");
            }
             areaId = areaIds.substring(0, areaIds.length()-1);
             areaName = areaNames.substring(0, areaNames.length()-1);
        }
        String commoditySort = data.getCommoditySort();
        String businessType = data.getBusinessType();
        if(StringUtils.isNotBlank(commoditySort)){
            //根据标志位的不同转换不同的数据
            map.put("commoditySort",  flag == true?commoditySort:cacheServ.queryData(
                    "commodity_sort", commoditySort, CodeList.class).getValue());
        }else{
            map.put("commoditySort", "");
        }
        if(StringUtils.isNotBlank(businessType)){
            map.put("businessType", flag == true?businessType:cacheServ.queryData(
                    "business_type", businessType, CodeList.class).getValue());
        }else{
            map.put("businessType", "");
        }
        map.put("commodityProducts", packCommodityProducts(data));
        map.put("id", data.getId());
        map.put("commodityName", data.getCommodityName());
        map.put("commodityCode", data.getCommodityCode());
        map.put("isGive", data.getIsGive());
        map.put("commoditySaledepartments", deptList);
        map.put("commodityEducational", studySystemList);
        map.put("commodityLevels", studyLevelList);
        map.put("commodityGrade", gradeList);
        map.put("commoditySpecialty", specialtyList);
        map.put("commodityUserType", userTypeList);
        map.put("areaIds", areaId);
        map.put("areaNames", areaName);
        return map;
    }

    /**
     * 转换商品查询条件下拉框参数
     * @param queryCondition
     * @return
     */
    private QueryCondition transformParams(QueryCondition queryCondition) {
        if(null != queryCondition.getProductDescId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getProductDescId().toString())){
                queryCondition.setProductDescId(null);
            }
        }
        if(null != queryCondition.getBusinessTypeId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getBusinessTypeId())){
                queryCondition.setBusinessTypeId(null);
            }
        }
        if(null != queryCondition.getEducationalId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getEducationalId())){
                queryCondition.setEducationalId(null);
            }
        }
        if(null != queryCondition.getGradeId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getGradeId())){
                queryCondition.setGradeId(null);
            }
        }
        if(null != queryCondition.getSpecialtyId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getSpecialtyId())){
                queryCondition.setSpecialtyId(null);
            }
        }
        if(null != queryCondition.getProductLineId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getProductLineId())){
                queryCondition.setProductLineId(null);
            }
        }
        if(null != queryCondition.getSaleDepartmentId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getSaleDepartmentId())){
                queryCondition.setSaleDepartmentId(null);
            }
        }
        if(null != queryCondition.getIsHasSaledate()){
            if(Constant.QUERY_ALL.equals(queryCondition.getIsHasSaledate().toString())){
                queryCondition.setIsHasSaledate(null);
            }
        }
        if(null != queryCondition.getAuditStatusId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getAuditStatusId().toString())){
                queryCondition.setAuditStatusId(null);
            }
        }
        if(null != queryCondition.getSaleStatusId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getSaleStatusId().toString())){
                queryCondition.setSaleStatusId(null);
            }
        }
        if(null != queryCondition.getGroundStatusId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getGroundStatusId().toString())){
                queryCondition.setGroundStatusId(null);
            }
        }
        if(null != queryCondition.getStudyLevelId()){
            if(Constant.QUERY_ALL.equals(queryCondition.getStudyLevelId())){
                queryCondition.setStudyLevelId(null);
            }
        }
        return queryCondition;
    }
}
